package util

import (
	"fmt"
	"strconv"
	"strings"
)

// 双指针
func UrlRange(start string, end string) (string, string, int, int, error) {
	start = strings.Trim(start, " ")
	end = strings.Trim(end, " ")
	prefix := ""
	suffix := ""
	startNum := 0
	endNum := 0
	//左右指针
	l := 0
	r := 0

	ls := len(start) - 1
	lr := len(end) - 1
	if strings.Index(start, "{") >= 0 && strings.Index(start, "}") >= 0 {
		l = strings.Index(start, "{") + 1
		r = ls - strings.Index(start, "}") + 1
	} else if strings.Index(start, "｛") >= 0 && strings.Index(start, "｝") >= 0 {
		l = strings.Index(start, "｛") + 1
		r = ls - strings.Index(start, "｝") + 1
	} else {
		for i := 0; i < ls; i++ {
			if start[l] == end[l] {
				l += 1
			}
			if start[ls-r] == end[lr-r] {

				r += 1
			}
			if l != i+1 && r != i+1 || l >= ls-r-1 {
				break
			}
		}
	}
	prefix = strings.Trim(start[0:l], " {}｛｝")
	suffix = strings.Trim(end[lr-r+1:], "  {}｛｝")
	startNumStr := start[l : ls-r+1]
	endNumStr := end[l : lr-r+1]
	startNum, err1 := strconv.Atoi(startNumStr)
	endNum, err2 := strconv.Atoi(endNumStr)
	fmt.Println(prefix, suffix, startNum, endNum, err1)
	if err1 != nil {
		return prefix, suffix, startNum, endNum, err1
	}
	if err2 != nil {
		return prefix, suffix, startNum, endNum, err2
	}
	return prefix, suffix, startNum, endNum, nil
}

// 找出出现最多的前缀
func UrlPrefix(strs []string) string {
	if len(strs) == 0 {
		return ""
	}

	// 初始化前缀计数器
	prefixCounts := make(map[string]int)

	// 计算所有字符串的最长可能长度
	maxLength := 0
	for _, str := range strs {
		if len(str) > maxLength {
			maxLength = len(str)
		}
	}
	res := ""
	// 遍历每个可能的前缀长度
	for length := 1; length <= maxLength; length++ {
		// 遍历所有字符串，提取前缀并计数
		for _, str := range strs {
			if len(str) < length {
				continue
			}
			prefix := str[:length]
			prefixCounts[prefix]++
		}
		tmp_res := ""
		// 检查是否有前缀的计数超过总数的65%
		for prefix, count := range prefixCounts {
			if count < len(strs)*13/20 {
				continue
			}
			if count >= len(strs)*13/20 {
				tmp_res = prefix
				//fmt.Println("linkcount", prefix, count, len(strs))
				break
			}
		}
		//还有值就继续匹配，知道匹配不上用上一个值
		if tmp_res != "" {
			res = tmp_res
		} else {
			if len(res) > 1 {
				res = res[:len(res)-1]
			}
			return res
		}

		// 重置前缀计数器，为下一个长度的前缀做准备
		prefixCounts = make(map[string]int)
	}
	fmt.Println("prefix", res)
	if len(res) > 1 {
		res = res[:len(res)-1]
	}
	fmt.Println("prefix", res)
	return res // 如果没有找到满足条件的前缀，则返回空字符串
}

// 检查最后2部分是否相等
func UrlCompare(u1 string, u2 string) bool {
	us1 := strings.Split(u1, "/")
	us2 := strings.Split(u2, "/")
	if len(us1) > 2 && len(us1) > 2 {
		if us1[len(us1)-1] == us2[len(us2)-1] && us1[len(us1)-2] == us2[len(us2)-2] {
			return true
		}
		return false
	}
	if len(us1) > 1 && len(us1) > 1 {
		if us1[len(us1)-1] == us2[len(us2)-1] {
			return true
		}
	}
	return false
}
